<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryParams" size="small" :inline="true" label-width="68px">
      <el-form-item label="设备" prop="deviceName">
        <el-select v-model="queryParams.deviceName" filterable placeholder="请选择设备"
                   @change="dataLocationAndNameByDeviceId">
          <el-option
            v-for="device in deviceList"
            :key="device.id"
            :label="device.name"
            :value="{ value: device.id, label: device.name }"
          ></el-option>
          <el-option  label="自定义查询" value="自定义查询"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="点位" prop="locationName">
        <el-select v-model="queryParams.locationName" filterable placeholder="请选择设备" @change="splitValue ">
          <el-option
            v-for="data in dataLocationLists"
            :key="data.id"
            :label="data.name"
            :value="{ value: data.id, label: data.name }"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="datetime">
        <el-date-picker
          v-model=queryParams.datetime
          align="right"
          type="date"
          placeholder="选择日期"
          :picker-options="pickerOptions"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="数据维度" prop="dimensions">
        <el-select v-model="queryParams.dimensions" placeholder="请选择数据维度" clearable>
          <el-option
            v-for="dict in dict.type.data_dimensions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-divider></el-divider>
    <el-row>
      <el-col :span="24" style="height: 742px;" id="charts" v-loading="loading"></el-col>
    </el-row>


  </div>
</template>

<script>

import {deviceLists} from "@/api/energy/equipment";
import {dataLocationAndNameByDeviceId} from "@/api/dataAnalysis/transient";
import {queryStatistics,customQueryStatistics } from "@/api/dataAnalysis/statistics";
import * as echarts from 'echarts';
import FileSaver from "file-saver";
import * as XLSX from 'xlsx'
import log from "@/views/monitor/job/log.vue";

export default {
  name: "Statistics",
  dicts: ['data_dimensions'],
  data: function () {
    return {
      loading: false,
      deviceList: [],
      dataLocationLists: [],
      chartsLegends: [],
      customQueryType:[
        {
          id:1,
          name: '合计发电量',
          location:'totalPowerGeneration'
        },
        {
          id:2,
          name:'合计发电时间',
          location: 'totalPowerGenTime'
        },
        {
          id:3,
          name:'生消差值',
          location: 'genComValue'
        }
      ],
      chart: null,
      chartList: [],
      chartOption: {
        xAxis: [],
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        toolbox: {
          show: true,
          feature: {
            magicType: {show: true, type: ['line', 'bar']},
            saveAsImage: {show: true},
            dataView: {
              show: true,
              lang: ['数据视图', '关闭', '导出Excel'],
              optionToContent: function (opt) {

                var axisData = opt.xAxis[0].data;
                var seriesArray = opt.series;
                var tdHeads = '<td  style="padding: 0 10px"></td>';
                for (let i in axisData) {
                  tdHeads += "<td style='padding: 0 10px'>" + axisData[i] + "</td>"
                }
                var table = '<table id="Mytable" border="1" class="table table-bordered table-striped table-hover" style="width:100%;text-align:center" ><tbody><tr>' + tdHeads + ' </tr>';
                for (let i in seriesArray) {
                  let row = "<tr><td style='padding: 0 10px'>" + seriesArray[i].name + "</td>"
                  for (let j in seriesArray[i].data) {
                    row += "<td style='padding: 0 10px'>" + seriesArray[i].data[j] + "</td>"
                  }
                  table += row + "</tr>";
                }
                table += '</tbody></table>';
                return table;
              },
              contentToOption: function (HTMLDomElement, opt) {
                let et = XLSX.utils.table_to_book(
                  document.getElementById("Mytable")
                );
                let etout = XLSX.write(et, {
                  bookType: "xlsx",
                  bookSST: true,
                  type: "array",
                });
                try {
                  FileSaver.saveAs(
                    new Blob([etout], {
                      type: "application/octet-stream",
                    }),
                    "统计数据" + "-" + new Date().toLocaleString() + ".xlsx"
                  );
                } catch (e) {
                }
                return etout;

              }

            },
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [],
        legend: {
          data: this.chartsLegends
        },
      },
      queryParams: {
        deviceId: null,
        deviceName: null,
        locationId: null,
        locationName: null,
        datetime: null,
        dimensions: null,
      },
      lastDimensions: null,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            picker.$emit('pick', new Date());
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24);
            picker.$emit('pick', date);
          }
        }, {
          text: '一周前',
          onClick(picker) {
            const date = new Date();
            date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', date);
          }
        }]
      },
      value: "",
    };
  },
  created() {
    this.deviceLists();
  },
  mounted() {
    this.initCharts();
  },
  methods: {
    initCharts() {
      this.chart = echarts.init(document.getElementById('charts'));
      this.chart.setOption(this.chartOption);
    },
    deviceLists() {
      deviceLists('2').then(res => {
        this.deviceList = res.data;
      });
    },
    splitValue(data) {
      const {value, label} = data;
      this.queryParams.locationId = value;
      this.queryParams.locationName = label;
    },
    dataLocationAndNameByDeviceId(data) {
      this.queryParams.locationId = null;
      this.queryParams.locationName = null;
      if (this.queryParams.deviceName == '自定义查询') {

        this.dataLocationLists = this.customQueryType;
        return;
      }
      const {value, label} = data;
      this.queryParams.deviceId = value;
      this.queryParams.deviceName = label;
      dataLocationAndNameByDeviceId(this.queryParams.deviceId, '2').then(res => {
        let data = res.data;
        if (data.length == 0) {
          this.$alert('改设备暂未配置点位', '信息', {
            confirmButtonText: '确定',
          });
          return
        }
        this.dataLocationLists = data;
      })
    },
    /** 搜索按钮操作 */

    handleQuery() {
      let lineName = this.queryParams.deviceName + ":" + this.queryParams.locationName + "(" + this.queryParams.datetime + ")";
      if (
        this.queryParams.datetime == null ||
        this.queryParams.locationId == null ||
        this.queryParams.dimensions == null) {
        this.$message({
          message: '请补全搜索条件',
          type: 'warning'
        });
        return
      }
      if (this.chartsLegends.indexOf(lineName) >= 0 && this.queryParams.dimensions == this.lastDimensions) {
        this.$message({
          message: '当前曲线已绘制',
          type: 'warning'
        });
        return;
      }
      this.loading = true;
      if (this.lastDimensions != null && this.lastDimensions != this.queryParams.dimensions) {
        this.$message({
          message: '对比维度变化,重绘数据中',
          type: 'warning'
        });
        this.resetCharts();
      }

      if (this.queryParams.deviceName == '自定义查询') {
        this.customSelectAndDraw(lineName);
      }else {
        this.selectAndDraw(lineName);

      }
    },
    selectAndDraw(lineName) {
      queryStatistics(this.queryParams).then(res => {
        this.loading = false;
        let data = res.data;
        this.draw(data,lineName);
      })
    },
    customSelectAndDraw(lineName) {
      customQueryStatistics(this.queryParams).then(res => {
        this.loading = false;
        let data = res.data;
        this.draw(data,lineName);
      })


    },
    draw(data,lineName) {
      if (data.hasOwnProperty("total")) {
        this.$alert(this.queryParams.deviceName + "截至当前时间" + this.queryParams.locationName + "累计数值为" + data.total, '累计数值', {
          confirmButtonText: '确定',
        });
        return;
      }
      if (data.xData.length == 0 || data.yData.length == 0) {
        this.$message('该点位在此时间段下暂无数据');
        return;
      }
      this.chartsLegends.push(lineName);
      if (this.lastDimensions == null) {
        this.chartOption.xAxis.push({
          type: 'category',
          data: data.xData
        });
      } else if (this.lastDimensions != this.queryParams.dimensions) {
        this.$delete(this.chartOption.xAxis, 0)
        this.chartOption.xAxis.push({
          type: 'category',
          data: data.xData
        });
      } else if (this.lastDimensions == this.queryParams.dimensions) {

        if (data.xData.length > this.chart.getOption().xAxis[0].data.length) {
          this.$delete(this.chartOption.xAxis, 0)
          this.chartOption.xAxis.push({
            type: 'category',
            data: data.xData
          });
        }
      }

      this.chartOption.series.push({
        name: lineName,
        type: 'bar',
        data: data.yData,
        label: {
          show: true,
          position: 'top'
        },
      });
      this.chart.setOption(this.chartOption);
      this.lastDimensions = this.queryParams.dimensions;

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.resetCharts()
    },
    /** 重置按钮操作 */
    resetCharts() {
      // this.chart.dispose();
      this.chartsLegends = [];
      // this.chartOption.series = [];
      // this.chartOption.xAxis = [];
      // this.initCharts();
      this.chartOption = this.chart.getOption();
      this.chartOption.series = [];
      //先更新曲线数据后更新x坐标，不可以一起更新
      this.chart.setOption(this.chartOption, true);

    },


  }
};
</script>

